package com.ljw.http.client;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author liujw
 * @create 2020/10/13 16:26
 */
public class OkHttp3Client {

    public static void main(String[] args) throws IOException {
        String urlPath = "https://10.10.20.143:28000/cfgmgr/queryPolicy";

        Map<String, String> headers = new HashMap<>(2);
        headers.put("csrfTokenHoneypot", "1c7cd1dcec5bbf358dfe25a7f99a25dfcf8ef81c3eb19a638bdd5072a7c4c6d5bbd503d27ab310b3b3125b760451efe0f8af363728aeea0dabf83b2b26337a9559adef4fd4a59c2580d934368e8b2b09d904f1cd39e506c2d9fbfba4f265e4ef6962bfe2cdedca64935bd9cd015ac998d22f890249d4e34f97bb8d5320c2fcb1ed296cd06bc7fc90683d1e03410526e9f65446958b9f3d9e6f40af090ce8d7c01a9a9fc7db9fa17e3c01d2d1df10e31f261dffead072c08b7d3ea941e58f12a2b6bdd7c4843892bd8fb4482b167e1c26e069347acf9bb067a59794d77b14107563b1c026d84eba4540d2b37ed2e61b008bb01def878125fc5cf32212c8e0947067008fd4265c6fc14ab429f1ab7b32c3");
        headers.put("Cookie", "JSESSIONID=A22D97F6DEE6DCB091B9F10253674213");

        String paramBody = "{\"currentPage\":1,\"pageSize\":1}";

        String result = send(urlPath, headers, paramBody, "POST");
        System.out.println(result);
    }

    public static String send(String urlPath, Map<String, String> headers, String paramBody, String method) {
        String result = null;
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        clientBuilder.connectTimeout(30, TimeUnit.SECONDS);
        try {
            TrustManager[] trustAllCerts = {new SslUtil.TrustAllManager()};
            clientBuilder.sslSocketFactory(SslUtil.buildSSLContext(trustAllCerts).getSocketFactory(), (X509TrustManager) trustAllCerts[0]);
            clientBuilder.hostnameVerifier((s, sslSession) -> true);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        Request.Builder builder = new Request.Builder().url(urlPath);
        if ("POST".equalsIgnoreCase(method)) {
            //MediaType  设置Content-Type 标头中包含的媒体类型值
            RequestBody requestBody = FormBody.create(paramBody, MediaType.parse("application/json; charset=utf-8"));
            builder.post(requestBody);
        } else if ("GET".equalsIgnoreCase(method)) {
            builder.get();
        } else {
            throw new RuntimeException("Method Not Support! Method is " + method);
        }

        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String value = entry.getValue();
                if (StringUtils.isNotBlank(value)) {
                    builder.header(entry.getKey(), value);
                }
            }
        }
        try {
            Response response = clientBuilder.build().newCall(builder.build()).execute();
            if (response.isSuccessful()) {
                result = response.body().string();
            } else {
                throw new RuntimeException("Failed! responseCode=" + response.code() + "message=" + response.message());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;
    }
}
